package com.yuanfeng.base.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanfeng.base.dto.BaseImConfigDTO;
import com.yuanfeng.base.entity.BaseImConfigEntity;
import com.yuanfeng.base.mapper.BaseImConfigMapper;
import com.yuanfeng.base.service.BaseImConfigService;
import com.yuanfeng.commoms.config.YFConfig;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.Json.JsonUtils;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.RedisUtil;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import org.springframework.stereotype.Service;

/**
 * @ClassName BaseImConfigServiceImpl
 * @Description
 * @Author cyp
 * @Date 2023-06-26 13:27:15
 * @Version 1.0
 **/
@Service
public class BaseImConfigServiceImpl extends ServiceImpl<BaseImConfigMapper, BaseImConfigEntity>
        implements BaseImConfigService {


    @Override
    public ResponseResult queryConfig() {
        String im_config = RedisUtil.get(YFConfig.IM_CONFIG);
        BaseImConfigEntity imConfig = JsonUtils.string2Obj(im_config, BaseImConfigEntity.class);
        if(null == imConfig){
            imConfig = this.baseMapper.queryConfig();
            RedisUtil.set(YFConfig.IM_CONFIG,JsonUtils.toString(imConfig));
        }
        return ResponseResult.success(imConfig);
    }

    @Override
    public ResponseResult updateImConfig(BaseImConfigDTO baseImConfigReq) {
        if (null != baseImConfigReq && null != baseImConfigReq.getToken()) {
            //校验token
            String token = baseImConfigReq.getToken();
            UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(token);
            if (null != userInfo) {

                Integer num = 0;
                if(null != baseImConfigReq && null != baseImConfigReq.getId()){
                    //修改im 配置
                    num = this.baseMapper.imConfigUpdate(baseImConfigReq);
                }else{
                    num = this.baseMapper.imConfigInsert(baseImConfigReq);
                }
                //删除redis中缓存
                if(num > 0 ){
                    RedisUtil.remove(YFConfig.IM_CONFIG);
                    return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
                }
                return ResponseResult.success(BizCodeEnume.OPERATION_FAILED);
            }
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
        }
        return ResponseResult.fail(BizCodeEnume.VALID_EXCEPTION);
    }
}
